
# Clean up
rm(list = ls())

# Set working directory; please set your own here
setwd("~/Dropbox/Fragmentation/fragmentation_replication_bjps/")

library(tidyverse)
library(foreign)

# Import dataset with results
dinas_only <- read.dta13("Results/analyses_final_dinasonly.dta")

# Defining line breaks in the type of outcome
levels(dinas_only$outcome_type) <- gsub("\\n", "\n", levels(dinas_only$outcome_type))

# Fixing levels in outcome and outcome_type variables
dinas_only$Outcome[dinas_only$Outcome == "Summary\\nmeasures (PCA)"] <- "Summary measures (PCA)"
dinas_only$Outcome[dinas_only$Outcome == "Repr underpriviliged\\ngroups (PCA)"] <- "Repr underpriviliged groups (PCA)"
dinas_only$outcome_type[dinas_only$outcome_type == "Summary\\nmeasures"] <- "Summary\nmeasures"
dinas_only$outcome_type[dinas_only$outcome_type == "Descriptive\\nrepr of women"] <- "Descriptive\nrepr of women"
dinas_only$outcome_type[dinas_only$outcome_type == "Repr underpriviliged\\ngroups"] <- "Repr underpriviliged\ngroups"
dinas_only$outcome_type[dinas_only$outcome_type == "Other\\noutcomes"] <- "Other\noutcomes"

# Creating a variable to order the plot by
dinas_only$order_outcome <- 1
dinas_only$order_outcome[dinas_only$outcome_type == "Summary\nmeasures"] <- 0
dinas_only$order_outcome[dinas_only$outcome_type == "Other\noutcomes"] <- 2

# Draw the actual plot
main_plot_dinas_only <- dinas_only %>%
  mutate(Outcome = fct_reorder(Outcome, pca)) %>%
  mutate(outcome_type = fct_reorder(outcome_type, order_outcome)) %>%
  ggplot(aes(Outcome, Effect, color = factor(pca), show.legend = FALSE)) + 
  geom_hline(aes(yintercept = 0), linetype = 2) + 
  coord_flip(ylim = c(-1, 1)) + 
  geom_linerange(aes(ymin = ci_lower, ymax = ci_upper), position = position_dodge(width = 0.75) ) + 
  geom_point(size = 1, position = position_dodge(width = 0.75) ) + 
  facet_grid(rows = vars(outcome_type),
             scales = "free_y") + 
  theme_minimal(base_size = 9) +
  theme(legend.position = "none",
        panel.background = element_rect(fill = NA, color = "black")) +
  scale_color_manual(values = c("black", "blue")) +
  ylab(" ") + 
  xlab("") 
main_plot_dinas_only

# Save the plot
ggsave("Plots/figd6.png", plot = main_plot_dinas_only, width = 25, height = 20, units = "cm")